<template>
  <div>
    <div v-if="initLoading">
      正在初始化配置数据...
    </div>
    <div v-else>
      <div v-if="!hasInit">
        <div v-if="!tableCode||tableCode.length===0">没有tableCode参数</div>
        <div v-else>初始化配置数据失败</div>
      </div>
      <div v-else>
        <ZgNewPage
          ref="page"
          :title="table.name"
          addBtnName="新增采集"
          :scrollX="2000"
          :pageOpt="pageOpt"
          :batchBtns="batchBtns"
          :dataBtns="dataBtns"
          @search="onSearch"
          @filter="onFilter"
          @add="toAdd"
          @batch="toBatch"
          @admin="toAdmin"
        >
          <template slot="columns">
            <a-table-column
              :width="column.width"
              v-for="(column,i) in columns"
              :key="`column${i}`"
              :dataIndex="column.code"
              :title="column.name">

            </a-table-column>
          </template>
          <template slot="condition">
            <Condition ref="condition" :formId="table.id" @search="onSearchWithCondition"></Condition>
          </template>
          <template slot="headerConfig">
            <HeaderConfig ref="headerConfig" :formCode="tableCode" @change="mergeHeader"></HeaderConfig>
          </template>
          <template slot="thMode" slot-scope="scope">
            <a-row>
              <a-col :span="4" v-for="t in scope.list" :key="`thMode_${t.id}`">
                <a-card>
                  <div class="wfull h100 scroll">
                    {{ t }}
                  </div>
                </a-card>
              </a-col>
            </a-row>
          </template>
        </ZgNewPage>
        <FormConfiguration ref="FormConfiguration"></FormConfiguration>
      </div>

    </div>

  </div>
</template>
<script>
import Add from './Add'
import Update from './Update'
import Batch from './Batch'
import Condition from './Condition'
import Info from './Info'
import Sort from './Sort'
import Config from './Config'
import HeaderConfig from './HeaderConfig'
import FormConfiguration from './FormConfig/FormConfiguration.vue'

export default {
  components: {
    Add, Update, Batch, Condition, Info, Sort, Config, HeaderConfig, FormConfiguration
  },
  computed: {
    sortedHeader () {
      const orderedArr = this.header.slice().sort((x, y) => x.sort - y.sort)
      return orderedArr
    }
  },
  data () {
    return {
      // dic,
      // showConfig: false,
      // title: '流程采集管理',
      // showInfo: false,
      // infoObj: null,
      // header: [
      //   { name: '流程名称', code: 'name', type: 'text', width: 120, isShow: true, sort: 1 },
      //   { name: '流程编号', code: 'code', type: 'text', width: 120, isShow: true, sort: 2 },
      //   { name: '流程版本', code: 'version', type: 'text', width: 120, isShow: true, sort: 3 },
      //   { name: '流程类型', code: 'type', type: 'dic', dicCode: 'flowType', width: 120, isShow: true, sort: 4 },
      //   { name: '流程分类', code: 'category', type: 'dic', dicCode: 'flowCategory', width: 120, isShow: true, sort: 5 },
      //   { name: '是否发布', code: 'isPublish', type: 'switch', width: 120, isShow: true, sort: 6 },
      //   { name: '后续流程编号', code: 'nextCode', type: 'text', width: 120, isShow: true, sort: 7 }
      // ],
      // pageOpt: {
      //   showConditionBtn: true,
      //   showBatchBtn: true,
      //   showBatchAddBtn: false,
      //   showHeaderConfig: true,
      //   showLayoutMode: false,
      //   showUpdateBtn: true,
      //   conditionHeight: 160,
      //   manageFilter: false
      // }
      hasInit: false,
      initLoading: false,
      tableCode: 'form_test',
      table: null,
      columns: [],
      addColumns: [],
      pageOpt: {
        showConditionBtn: true,
        showHeaderConfig: true,
        showAttachBtn: true,
        showLayoutMode: true
      },
      batchBtns: [

        { key: 1, label: '模板下载' }
        // { key: 2, label: '批量修改' },
        // { key: 3, label: '数据排序' },
        // { key: 4, label: 'Excel导入' },
        // { key: 5, label: 'Excel导出' }
      ],
      dataBtns: [

        { key: 1, name: '表单配置', icon: 'fa-setting', isShow: () => { return true } },
        { key: 2, name: '环节设计', icon: 'fa-gateway', isShow: () => { return true } },
        { key: 3, name: '控件配置', icon: 'tool', isShow: () => { return true } },
        { key: 4, name: '重新导入', icon: 'plus', isShow: () => { return true } },
        { key: 5, name: '导出', icon: 'export', isShow: () => { return true } },
        { key: 6, name: '删除', icon: 'fa-trash', isShow: () => { return true } }
      ],
      extra: {
        表单编码: '',
        属性列表: '',
        枚举编码: '',
        字典类型: '',
        行数: '3',
        高度: '400'
      },
      testData: [
        {
          id: 1,
          name: '张三',
          intro: 18,
          info: 18,
          age: 18,
          score: 18,
          is_test: 18,
          political: 18,
          is_use: 18,
          birth: 18,
          last_login_time: 18,
          total: 18
        }
      ]

    }
  },
  mounted () {
    this.init()
  },
  methods: {
    // saveHeader () {
    //   this.$http.post('/zg-autoform/header/config/update', {
    //     formCode: 'flow_def',
    //     headerList: this.header.map(t => {
    //       return {
    //         formCode: 'flow_def',
    //         columnCode: t.code,
    //         width: t.width,
    //         label: t.name,
    //         isShow: t.isShow,
    //         sort: t.sort
    //       }
    //     })
    //   }, () => {
    //     this.$success({ title: '保存成功' })
    //   })
    // },
    // loadUserHeader () {
    //   this.$http.post('/zg-generator/config/column/list', {
    //     schema: 'base',
    //     tableName: 'flow_def'
    //   }, data => {
    //     const defaultHeader = data.map(t => {
    //       return {
    //         name: t.headerName,
    //         code: t.columnName,
    //         type: t.compType,
    //         dicCode: t.dicCode,
    //         width: t.headerWidth,
    //         isShow: t.headerShow,
    //         sort: t.headerSort
    //       }
    //     })
    //     this.$http.get('/zg-autoform/header/config/list', {
    //       formCode: 'flow_def'
    //     }, data => {
    //       if (data.length > 0) {
    //         defaultHeader.map(t => {
    //           const arr = data.filter(x => {
    //             return x.columnCode === t.code
    //           })
    //           if (arr.length > 0) {
    //             t.name = arr[0].label
    //             t.width = arr[0].width
    //             t.isShow = arr[0].isShow
    //             t.sort = arr[0].sort
    //           }
    //         })
    //       }
    //       this.header = defaultHeader
    //     })
    //   })
    // },
    // loadDefaultHeader () {
    //   this.$http.post('/zg-generator/config/column/list', {
    //     schema: 'base',
    //     tableName: 'flow_def'
    //   }, data => {
    //     this.header = data.map(t => {
    //       return {
    //         name: t.headerName,
    //         code: t.columnName,
    //         type: t.compType,
    //         dicCode: t.dicCode,
    //         width: t.headerWidth,
    //         isShow: t.headerShow,
    //         sort: t.headerSort
    //       }
    //     })
    //   })
    // },
    // onSortEnd () {
    //   setTimeout(() => {
    //     this.header = this.header.map((t, i) => {
    //       t.sort = i
    //       return t
    //     })
    //   }, 200)
    // },
    // getOptLabel (opts, value) {
    //     const arr = opts.filter(t => {
    //         return t.value === value
    //     })
    //     if (arr.length > 0) {
    //         return arr[0].label
    //     } else {
    //         return ''
    //     }
    // },
    onSearch (param) {
       this.$refs.page.endSearch(
          {
            total: parseInt(100),
            list: this.testData.map(t => {
              t.key = t.id
              return t
            })
          }
        )
      this.$http.get('/zg-autoflow/flow/def/page', param, data => {
        this.$refs.page.endSearch(
          {
            total: parseInt(data.total),
            list: data.records.map(t => {
              t.key = t.id
              return t
            })
          }
        )
      })
    },
    onFilter (f, param) {
      // 切换数据视图
      this.$refs.condition.setCondition(f.condition)
      this.onSearchWithCondition(param)
    },
    toAdd () {
      // 新增采集
      this.$refs.add.open()
    },
    toBatch (opt) {
      if (opt.key === 1) {
        this.$refs.page.checkIds(ids => {
          this.$http.post('/zg-autoform/table/data/del/' + this.table.code, ids, () => {
            this.$refs.page.search()
          })
        }, '确定要批量删除这些数据')
      } else if (opt.key === 2) {
        this.$refs.page.checkIds(ids => {
          this.$refs.batch.open(ids)
        }, '确定要批量修改这些数据')
      } else if (opt.key === 3) {
        const list = this.$refs.page.getList()
        this.$refs.sort.open(list)
      } else if (opt.key === 4) {
        this.$refs.import.open()
      } else if (opt.key === 5) {
        this.$http.download('/zg-system/dict/export', {}, '字典数据.xlsx')
      }
    },
    toAdmin (param) {
      if (param.key === 1) {
        // 表单配置
        this.$refs.FormConfiguration.open()
      } else if (param.key === 2) {
        // 环节设计
        this.$refs.update.open(param.obj)
      } else if (param.key === 3) {
        // 控件配置
        this.$refs.attach.open(param.obj)
      } else if (param.key === 4) {
        // 重新导入
      } else if (param.key === 5) {
        // 导出
      } else {
        // 删除
        this.confirm(
          () => {
            this.$http.post('/zg-autoform/table/data/del/' + this.table.code, [param.obj.id], () => {
              this.$refs.page.search()
            })
          },
        '确定要删除这条数据么')
      }
    },
    onSearchWithCondition (param) {
      const condition = this.$refs.condition.getParam()
      this.$http.get('/zg-autoflow/flow/def/page', Object.assign({}, param, condition), data => {
        this.$refs.page.endSearch(
          {
            total: parseInt(data.total),
            list: data.records.map(t => {
              t.key = t.id
              return t
            })
          }
        )
      })
    },
    init () {
      this.hasInit = false
      // this.tableCode = this.$route.query.tableCode
      if (!this.tableCode || this.tableCode.length === 0) {
        return
      }
      this.initLoading = true
      const timer = setTimeout(() => {
        this.initLoading = false
      }, 10000)
      this.$http.get('/zg-autoform/form/oneByCode', { code: this.tableCode }, data => {
        this.pageOpt.showConditionBtn = data.hasFilter
        data.addColumns.forEach(c => {
          c.code = c.code.toLowerCase()
          try {
            c.extra = Object.assign({}, this.extra, JSON.parse(c.extra))
          } catch (e) {
            c.extra = JSON.parse(JSON.stringify(this.extra))
          }
        })
        data.updateColumns.forEach(c => {
          c.code = c.code.toLowerCase()
          try {
            c.extra = Object.assign({}, this.extra, JSON.parse(c.extra))
          } catch (e) {
            c.extra = JSON.parse(JSON.stringify(this.extra))
          }
        })
        data.batchColumns.forEach(c => {
          c.code = c.code.toLowerCase()
          try {
            c.extra = Object.assign({}, this.extra, JSON.parse(c.extra))
          } catch (e) {
            c.extra = JSON.parse(JSON.stringify(this.extra))
          }
        })
        data.allColumns.forEach(c => {
          c.code = c.code.toLowerCase()
        })
        this.table = data
        this.findFilter()
        this.allColumns = data.allColumns
        this.mergeHeader(data.headers)
        clearTimeout(timer)
        this.initLoading = false
        this.hasInit = true
      }, (res) => {
        this.errorMsg = res.message
        this.initLoading = false
      })
    },
    findFilter () {
      /*
      this.$http.get('/zg-autoform/filter/list', { formId: this.table.id }, data => {
        const arr = [].concat(data[0]).concat(data[1])
        this.$refs.page.addFilter(arr.map(t => {
          return {
            id: t.id,
            name: t.name,
            condition: t.condition,
            count: 5
          }
        }))
      }) */
    },
    mergeHeader (headers) {
      if (!headers) {
        return this.allColumns
      }
      let result = this.allColumns.map(t => {
        const arr = headers.filter(x => {
          return x.columnCode === t.code
        })
        t.width = arr.length > 0 ? arr[0].width : 120
        t.sort = arr.length > 0 ? arr[0].sort : 0
        t.isShow = arr.length > 0 ? arr[0].isShow : true
        return t
      })
      result = result.filter(t => {
        return t.isShow
      })
      result.sort((a, b) => {
        return a.sort - b.sort
      })
      this.columns = result
    }
    // onDel (ids) {
    //   this.$http.post('/zg-autoflow/flow/def/del', ids, () => {
    //     this.$refs.page.search()
    //   })
    // },
    // onAdd () {
    //   const result = this.$refs.add.save()
    //   if (!result.isOk) {
    //     this.$error({ title: result.msg })
    //     return
    //   }
    //   this.$http.post('/zg-autoflow/flow/def/add', result.data, () => {
    //     this.$refs.page.hideAdd()
    //     this.$refs.page.search()
    //   })
    // },
    // onUpdate () {
    //   const result = this.$refs.update.save()
    //   if (!result.isOk) {
    //     this.$error({ title: result.msg })
    //     return
    //   }
    //   this.$http.post('/zg-autoflow/flow/def/update', result.data, () => {
    //     this.$refs.page.hideUpdate()
    //     this.$refs.page.search()
    //   })
    // },
    // onBatch () {
    //   const result = this.$refs.batch.save()
    //   if (!result.isOk) {
    //     this.$error({ title: result.msg })
    //     return
    //   }
    //   this.$http.post('/zg-autoflow/flow/def/batch', result.data, () => {
    //     this.$refs.page.hideBatch()
    //     this.$refs.page.search()
    //   })
    // },
    // onSort () {
    //   const result = this.$refs.sort.save()
    //   if (!result.isOk) {
    //     this.$error({ title: result.msg })
    //     return
    //   }
    //   const sortStr = result.data.map(t => {
    //     return t.id + '_' + t.index
    //   }).join(',')
    //   this.$http.post('/zg-autoflow/flow/def/sort', sortStr, () => {
    //     this.$refs.page.hideSort()
    //     this.$refs.page.search()
    //   })
    // },
    // onResetCondition () {
    //   this.$refs.condition.reset()
    // },

    // onExtraBtn (param) {
    //   if (param.key === 1) {
    //     this.infoObj = param.obj
    //     this.showInfo = true
    //   } else if (param.key === 2) {
    //     this.$http.post('/zg-autoflow/flow/def/update', {
    //       id: param.obj.id,
    //       isPublish: true
    //     }, () => {
    //       this.$refs.page.search()
    //     })
    //   } else if (param.key === 3) {
    //     this.$http.post('/zg-autoflow/flow/def/update', {
    //       id: param.obj.id,
    //       isPublish: false
    //     }, () => {
    //       this.$refs.page.search()
    //     })
    //   } else if (param.key === 4) {
    //     this.showConfig = true
    //   }
    // }
  }
}
</script>

<style lang="scss" scoped>
.chosen{
  border:solid 1px #096daf;
  background:#096daf;
  color:#fff;
}
</style>
